package com.argrace.smart.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.glide.GliderImageLoaderUtil;
import com.argrace.smart.model.LocalDb_QingJing_DeviceTable;
import com.argrace.smart.ui.DrawableSwitch;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by argrace_dev_1 on 2018/2/12.
 */

public class DeviceControl_ChaZuoActivity extends BaseActivity {
    private TextView kaiguan1_text, kaiguan2_text, kaiguan3_text;
    private TextView dianya, dianliu, dianliang;
    private DrawableSwitch switch1, switch2, switch3;
    MineZigBeeDeviceListEntity bean;
    private ImageView img;
    private int type = ConstantConfigure.TYPE_CONTROL;
    private String name;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicecontrol_chazuo);
        init();
    }

    private void init() {
        bean = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        name = getIntent().getStringExtra("name");
        type = getIntent().getIntExtra("type", ConstantConfigure.TYPE_CONTROL);
        setView();
        setTitle(true, false, bean.getName());
        if (type == ConstantConfigure.TYPE_SETTING) {
            //进入设备修改保存状态界面
            showRight(true, R.mipmap.head_title_tick);
            setLeftandRightClickListeners(null, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String str_params = translateParams();
                    LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                    entity.setJson_params(str_params);
                    entity.updateAll("uuid = ? and LocalDb_DeviceTable_deviceId = ?", bean.getUuid(), name);
                    finish();
                }
            });
        } else {
            showRight(true, R.mipmap.icon_modify);
            setLeftandRightClickListeners(null, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(DeviceControl_ChaZuoActivity.this, DeviceModifyActivity.class);
                    intent.putExtra("uuid", bean.getUuid());
                    intent.putExtra("model", bean.getModel());
                    startActivity(intent);
                }
            });
        }
        setCanClick(false);
        getDeviceDetailInfo();
    }

    private void setView() {
        img = (ImageView) findViewById(R.id.activity_devicecontrol_img);
        String imgurl = null;
        dianliu = (TextView) findViewById(R.id.activity_devicecontrol_chazuo_dianliu);
        dianya = (TextView) findViewById(R.id.activity_devicecontrol_chazuo_dianya);
        dianliang = (TextView) findViewById(R.id.activity_devicecontrol_chazuo_dianliang);
        kaiguan1_text = (TextView) findViewById(R.id.activity_devicecontrol_kaiguan1_text);
        kaiguan2_text = (TextView) findViewById(R.id.activity_devicecontrol_kaiguan2_text);
        kaiguan3_text = (TextView) findViewById(R.id.activity_devicecontrol_kaiguan3_text);
        switch1 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_kaiguan1);
        switch2 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_kaiguan2);
        switch3 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_kaiguan3);
        if (bean.getModel().equals(ConstantConfigure.MODEL_10ACHAZUO)) {
            imgurl = ConstantConfigure.IMGURL_10AZHINENGCHAZUO_000A1E11;
            kaiguan1_text.setText("童锁开关");
            kaiguan2_text.setText("插孔开关1");
            kaiguan3_text.setText("插孔开关2");
            switch1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = switch1.isSwitchOn() ? 0 : 1;
                    switch1.setSwitchOn(!switch1.isSwitchOn());
                    switch1.invalidate();
                    sendMsg("SwitchChildLock", String.valueOf(state));
                }
            });
            switch2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = switch2.isSwitchOn() ? 0 : 1;
                    switch2.setSwitchOn(!switch2.isSwitchOn());
                    switch2.invalidate();
                    sendMsg("SwitchMultiple_1", String.valueOf(state));
                }
            });
            switch3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = switch3.isSwitchOn() ? 0 : 1;
                    switch3.setSwitchOn(!switch3.isSwitchOn());
                    switch3.invalidate();
                    sendMsg("SwitchMultiple_2", String.valueOf(state));
                }
            });
        }
        if (imgurl != null) {
            GliderImageLoaderUtil.load(this, imgurl, img);
        }
    }

    private void setCanClick(boolean value) {
        LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
        if (value) {
        } else {
            ll.setOnClickListener(null);
            ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toastActBtm("不可点击");
                }
            });
        }
    }

    private void sendMsg(String key, String value) {
        if (type == ConstantConfigure.TYPE_SETTING) {
            return;
        }
        String method = "mtop.openalink.app.core.device.set.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        params.put("setParams", "{\"" + key + "\":\"" + value + "\"}");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Log.i("info", "发送消息成功" + transitoryResponse.data);
//                getDeviceDetailInfo();
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "发送消息失败");
            }
        });
    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);

                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                fillData(obj, obj.getString("uuid"));
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    @Override
    protected void dorecieve(JSONObject obj) {
        super.dorecieve(obj);
        if (type == ConstantConfigure.TYPE_SETTING) {
            return;
        }
        if (obj == null || obj.getJSONObject("params") == null || obj.getJSONObject("params").getJSONObject("data") == null || obj.getJSONObject("params").getString("uuid") == null) {
            return;
        }
        fillData(obj.getJSONObject("params").getJSONObject("data"), obj.getJSONObject("params").getString("uuid"));
    }

    private void fillData(JSONObject obj, String uuid) {
        if (uuid == null || !uuid.equals(bean.getUuid())) {
            return;
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_10ACHAZUO)) {
            Key_ValueEntity bean1 = JSON.parseObject(obj.getString("SwitchChildLock"), Key_ValueEntity.class);
            Key_ValueEntity bean2 = JSON.parseObject(obj.getString("SwitchMultiple_1"), Key_ValueEntity.class);
            Key_ValueEntity bean3 = JSON.parseObject(obj.getString("SwitchMultiple_2"), Key_ValueEntity.class);

            Key_ValueEntity bean4 = JSON.parseObject(obj.getString("RmsCurrent"), Key_ValueEntity.class);
            Key_ValueEntity bean5 = JSON.parseObject(obj.getString("RmsVoltage"), Key_ValueEntity.class);
            Key_ValueEntity bean6 = JSON.parseObject(obj.getString("SumElectric"), Key_ValueEntity.class);
            if (bean6 != null) {
                dianliang.setText(bean6.getValue() + "A");
            }
            if (bean5 != null) {
                dianya.setText(bean5.getValue() + "V");
            }
            if (bean4 != null) {
                dianliu.setText(bean4.getValue() + "KWH");
            }
            if (bean1 != null &&bean1.getValue().equals("0")) {
                switch1.setSwitchOn(false);
            } else {
                switch1.setSwitchOn(true);
            }
            switch1.invalidate();
            if (bean2 != null &&bean2.getValue().equals("0")) {
                switch2.setSwitchOn(false);
            } else {
                switch2.setSwitchOn(true);
            }
            switch2.invalidate();
            if (bean3 != null &&bean3.getValue().equals("0")) {
                switch3.setSwitchOn(false);
            } else {
                switch3.setSwitchOn(true);
            }
            switch3.invalidate();
        }
    }

    private String translateParams() {
        //0关闭，1开启
        Map<String, String> params = new HashMap<>();
        if (switch1.isSwitchOn()) {
            params.put("SwitchChildLock", "1");
        } else {
            params.put("SwitchChildLock", "0");
        }
        if (switch2.isSwitchOn()) {
            params.put("SwitchMultiple_1", "1");
        } else {
            params.put("SwitchMultiple_1", "0");
        }
        if (switch3.isSwitchOn()) {
            params.put("SwitchMultiple_2", "1");
        } else {
            params.put("SwitchMultiple_2", "0");
        }
        return utils.getTheJson(params);
    }
}
